import 'package:flutter/services.dart';
import 'dart:collection';

class FlutterBridgeChannel {
  static const channel = MethodChannel('Flutter_Channel');

  Future<String> _channelFunc(String funcName) async {
    return await channel.invokeMethod(funcName);
  }

  Future<void> channelMessage() async {
    String result = "调用原生";
    try {
      result = await _channelFunc("Native");
    } on PlatformException catch (e) {
      result = "请继续点击，但每次会 +2 !";
    }
  }

  Future<void> channelText() async {
    String result = "调用原生";
    try {
      result = await _channelFunc("Text");
    } on PlatformException catch (e) {
      result = "请继续点击，但每次会 +3 !";
    }
  }

  Future<void> channelBack() async {
    String result = "调用原生";
    try {
      result = await _channelFunc("Back");
    } on PlatformException catch (e) {
      result = "请继续点击，但每次会 +4 !";
    }
  }
}

class FlutterBridge {
  // 单例模式
  static FlutterBridge? _instance;
  // 定义通道名称 交互双方保持一致
  static const _channelName = "flutter_bridge";

  FlutterBridge._internal();
  // 获取实例对象
  static FlutterBridge? getInstance() {
    if (_instance == null) {
      // 初始化通道管理
      _instance = FlutterBridge._internal();
      // 初始化通道内容
      _methodChannel = const MethodChannel(_channelName);
      _callbackMap = HashMap();
    }
    return _instance;
  }

  // 私有构造
  _initChannel() {}

  // 私有 通道 初始化过程中
  static MethodChannel? _methodChannel;

  // 私有 回调 Map
  static HashMap<String, Callback>? _callbackMap;

  // 给原生发送
  static sendNative(
      String func, HashMap<String, Object?> params, Callback? callback) {
    // params 转为 json 字符串

    // 反射调用原生方的方法
    _methodChannel?.invokeMethod(func);
    // _methodChannel?.binaryMessenger.send(_channelName, params);
  }
}

class Callback {
  // 成功回调
  void succeed(HashMap<String, Object> params) {}

  // 失败回调
  void failed(int code, String msg) {}
}
